package ru.hh.team02.chat.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import ru.hh.team02.chat.utils.StringSocket;

/*
 * dummy client for testing purposes
 */
public class TestClient {
    private StringSocket requestSocket;
    
    private InputStreamReader converter = 
            new InputStreamReader(System.in);
    private BufferedReader consoleIn = 
            new BufferedReader(converter);
    
    public static void main(final String args[]) {
        TestClient client = new TestClient();
        client.run();
    }
    
    private void run() {
        try {
            requestSocket = new StringSocket(new Socket("localhost", 2004));
            System.out.println("connected to localhost in port 2004");
                        
            String message = "";
            do {                
                if (System.in.available() > 0) {
                    message = consoleIn.readLine();
                    requestSocket.write(message);
                }
                
                if (requestSocket.available()) {
                    handleMessage(requestSocket.read());
                }
            } while (!message.equals("exit"));
        } catch (UnknownHostException unknownHost) {
            System.err.println("You are trying to connect to an unknown host!");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        } finally {
            if (requestSocket != null) requestSocket.close();
            closeConsoleStreams();
        }
    }
    
    private void handleMessage(String message) {
        System.out.println(message);
    }
    
    private void closeConsoleStreams() {
        try {
            consoleIn.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                converter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
